package com.iflytek.cosmo.ocr.support.license;

import java.util.List;

import com.iflytek.cosmo.ocr.support.license.client.AbstractClientLicenseProcessor;
import com.iflytek.cosmo.ocr.support.license.client.ClientLicense;
import com.iflytek.cosmo.ocr.support.license.server.AbstractServerLicenseProcessor;
import com.iflytek.cosmo.ocr.support.license.server.ServerLicense;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2021/2/5
 */
@Component
@Data
public class LicenseManager {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private List<AbstractClientLicenseProcessor> clientProcessors;

    @Autowired
    private List<AbstractServerLicenseProcessor> serverProcessors;

    /**
     * 验证该授权码是否为结果RSA处理
     *
     * @param license 授权码
     *
     * @return
     */
    public boolean isRSALicense(String license) {
        return AbstractClientLicenseProcessor.decodeBaseInfo(license) != null;
    }

    /**
     * 调用对应版本的授权码验证器解码
     *
     * @param code 授权码
     *
     * @return null:授权码不合法
     */
    public ClientLicense decodeClient(String code) {
        // 只有先解密基础信息, 才能确定版本号, 进而调用对应版本的处理器
        ClientLicense license = AbstractClientLicenseProcessor.decodeBaseInfo(code);
        if (license == null) {
            return null;
        }

        int version = license.getVersion();
        for (AbstractClientLicenseProcessor processor : clientProcessors) {
            if (processor.supportVersion().getCode() == version) {
                return processor.decode(code);
            }
        }

        return null;
    }

    /**
     * 调用对应版本的授权码验证器解码
     *
     * @param code 授权码
     *
     * @return null:授权码不合法
     */
    public ServerLicense decodeServer(String code) {
        // 只有先解密基础信息, 才能确定版本号, 进而调用对应版本的处理器
        ServerLicense license = AbstractServerLicenseProcessor.decodeBaseInfo(code);
        if (license == null) {
            return null;
        }

        int version = license.getVersion();
        for (AbstractServerLicenseProcessor processor : serverProcessors) {
            if (processor.supportVersion().getCode() == version) {
                return processor.decode(code);
            }
        }

        return null;
    }
}
